<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <count></count>
  </div>
  <script src="./vue.js"></script>
  <script src="./vuex.js"></script>
  <script>
    const store = new Vuex.Store({
      state: {
        count: 0
      },
      mutations: {
        changeCount (state, num) {
          state.count += num
        }
      },
      actions: {
        getCount ({commit}, num) {
          setTimeout(() => {
            commit('changeCount', num)
          }, 2000)
        }
      }
    })


    const count = {
      template: `
        <div>
          <button @click="add">+1</button>
          <button @click="minus">-1</button>
          <button @click="asyncAdd">异步+1</button>

          <hr>
          <span>{{count}}</span>
        </div>
        
      `,
      computed: {
        count () {
          return this.$store.state.count
        }
      },
      methods: {
        add () {
          // 想要修改state中的 需要提交对应的mutation
          this.$store.commit('changeCount', 1)
        },
        minus () {
          this.$store.commit('changeCount', -1)
        },
        asyncAdd () {
          // 异步操作需要分发action
          this.$store.dispatch('getCount', 1)
        }
      }
    }
    

    const app = new Vue({
      el: '#app',
      store,
      components: {
        count
      }
    })
  </script>
</body>
</html>